package main

import (
	"fmt"
	"strings"
	"sync"
)

type UnorderedTree struct {
	Mux sync.Mutex
	Name string
	Children []*UnorderedTree
}

func NewTree() *UnorderedTree {
	return &UnorderedTree{
		Children:make([]*UnorderedTree, 0),
	}
}

func (ut *UnorderedTree)AddChild(name string)  {
	tree := NewTree()
	tree.Name = name

	ut.Children = append(ut.Children, tree)
}

func (ut *UnorderedTree)AddChildAndReturnNext(name string) *UnorderedTree {
	tree := NewTree()
	tree.Name = name

	// 如果有重复节点，直接返回
	for _, v := range ut.Children {
		if v.Name == name {
			return v
		}
	}

	ut.Children = append(ut.Children, tree)
	return tree
}

func (ut *UnorderedTree)Find(name string) []*UnorderedTree {
	res := make([]*UnorderedTree, 0)
	for _, v := range ut.Children {
		if v.Name == name || name == "+" {
			fmt.Println("添加孩子: ", v.Name, " 所有孩子: ", len(ut.Children))
			res = append(res, v)
		}
	}

	return res
}

type Res struct {
	Data []*UnorderedTree
}

// find: 1/+/3
func Scan(topic string, ut *UnorderedTree, r *Res) {
	fmt.Println("当前节点", ut.Name)
	split := strings.SplitN(topic, "/", 2)
	if len(split) == 1 {
		ch := ut.Find(split[0])
		for _, v := range ch {
			fmt.Println(ut.Name, "结果添加节点", v.Name)
			r.Data = append(r.Data, v)
		}

		return
	}

	if len(split) == 2 {
		ch := ut.Find(split[0])
		for _, v := range ch {
			fmt.Println("递归", len(ch), split[1])
			Scan(split[1], v, r)
		}
	}

	return
}

func main() {
	root := NewTree()
	root.Name = "root"

	// 添加root/1/2/3
	root.AddChildAndReturnNext("1").AddChildAndReturnNext("2").AddChildAndReturnNext("3").AddChildAndReturnNext("4")
	// 添加 1/+/2
	root.AddChildAndReturnNext("1").AddChildAndReturnNext("+").AddChildAndReturnNext("3").AddChildAndReturnNext("5")

	res := &Res{
		Data: make([]*UnorderedTree, 0),
	}
	Scan("1/+/3", root, res)

	fmt.Println(len(res.Data))
}
